package com.fastcms.cms.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fastcms.cms.entity.Article;
import com.fastcms.cms.entity.ArticleCategory;
import com.fastcms.cms.service.IArticleCategoryService;
import com.fastcms.cms.service.IArticleService;
import com.fastcms.cms.service.ISeoService;
import com.fastcms.common.utils.StrUtils;

/**
 * 律所入驻服务实现类
 * @author wjun_java@163.com
 * @since 2021-05-23
 */
@Lazy
@Service
public class SeoServiceImpl implements ISeoService {
	
	Logger logger=LoggerFactory.getLogger(this.getClass());

    static final String UNDERLINE = StrUtils.UNDERLINE;
    static final String WEBSITE_URL = "https://www.guliem.com";
    static final String DEFAULT_SEO_URL_VIEW = "seo_url";
    static final int TEXT_LINES_LIMIT = 50000;
    
    @Value("${seo.textDir}")
    private String textDir;
    
    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleCategoryService articleCategoryService;
    
	@Override
	public String genUrlTxt() {
    	StopWatch watch=new StopWatch("seo gen url.txt");
    	watch.start("query ids");
        List<String> urls=new ArrayList<String>();
        urls.add(WEBSITE_URL);
        urls.add(WEBSITE_URL+"/c/qa.html");
        
        List<ArticleCategory> categories = articleCategoryService.getArticleCategoryListByParentId(2l);
        for(ArticleCategory c:categories) {
        	StringBuilder sb=new StringBuilder();
        	sb.append(WEBSITE_URL).append("/c/").append(c.getId()).append(".html");
        	urls.add(sb.toString());
        }
        
    	QueryWrapper<Object> queryWrapper = Wrappers.query().eq("a.status", Article.STATUS_PUBLISH).orderByAsc("a.id");
    	for(int i=0;i<Integer.MAX_VALUE;i++) {	
    		Page<Long> pageVo = articleService.pageArticleId(new Page<Long>(i,1000),queryWrapper);
    		List<Long> records = pageVo.getRecords();
    		if(records.isEmpty()) {
    			break;
    		}
        	for(Long o:records) {
            	StringBuilder sb=new StringBuilder();
            	sb.append(WEBSITE_URL).append("/a/").append(o).append(".html");
            	urls.add(sb.toString());
            }
    	}
    	watch.stop();
    	watch.start("build url files");
        writeToFile(textDir,"url",urls);
        watch.stop();
        return watch.prettyPrint();
    }
    
    public void writeToFile(String dir,String name,List<String> urls) {
		int urlTotal = urls.size();
		List<List<String>> list = splitList(urls, TEXT_LINES_LIMIT);
		logger.info("urls total:{},files total:{}", urlTotal, list.size());
		for (int i = 0; i < list.size(); i++) {
			File _dir = new File(dir);
			if (!_dir.exists()) {
				_dir.mkdir();
			}
			String path = dir + name + i + ".txt";
			File file = new File(path);
			logger.info("generate {} start...", path);
			try {
				FileUtils.writeLines(file, list.get(i), false);
			} catch (IOException e) {
				e.printStackTrace();
			}
			logger.info("generate {} completed.", path);
		}
	}

	public static <T> List<List<T>> splitList(List<T> list, int pageSize) {
		List<List<T>> result = new ArrayList<List<T>>();
		List<T> subList = null;
		for (int i = 0; i < list.size(); i++) {
			if (i % pageSize == 0) {
				subList = new ArrayList<T>();
				result.add(subList);
			}
			subList.add(list.get(i));
		}
		return result;
	}
	

}
